<template>
  <div>
    <el-steps :active="step" simple>
      <el-step title="选择节目及设备" icon="el-icon-edit" v-if="step===1 || step===2 || step===3 || step===4"></el-step>
      <el-step title="设置日程并发布" icon="el-icon-upload" v-if="step===2 || step===3 || step===4"></el-step>
      <el-step title="审批" icon="el-icon-time" v-if="step===3 || step===4"></el-step>
      <el-step title="发布" icon="el-icon-check" v-if="step===4"></el-step>
    </el-steps>
    <div style="height: 10px;"></div>
    <div v-show="step == 1 && !channelQuick">
      <el-collapse :value="['1', '2']">
        <el-collapse-item title="节目列表" name="1">
          <el-button type="primary" @click="selectTheme" size="mini">添加节目</el-button>
          <el-table size="mini" :data="themeList" max-height="320" @selection-change="themeSelectionChange" style="width: 100%;" v-if="themeList.length > 0">
            <el-table-column type="selection" header-align="center" align="center" width="30"></el-table-column>
            <!--<el-table-column-->
            <!--prop="id"-->
            <!--header-align="center"-->
            <!--align="center"-->
            <!--label="ID">-->
            <!--</el-table-column>-->
            <el-table-column prop="programName" header-align="center" align="center" label="节目名称"></el-table-column>
            <el-table-column prop="canvasHeight" header-align="center" align="center" label="分辨率">
              <template slot-scope="scope">
                {{ scope.row.width }} * {{ scope.row.height }}
              </template>
            </el-table-column>
          </el-table>
          <el-button @click="delThemes" v-if="themeList.length > 0" style="margin-top: 10px;" type="warning" size="mini">删除</el-button>
        </el-collapse-item>
        <el-collapse-item title="设备列表" name="2">
          <el-button type="primary" @click="selectDevice" size="mini">添加设备</el-button>
          <el-table size="mini" :data="deviceList" max-height="320" @selection-change="deviceSelectionChange" style="width: 100%;" row-key="id" v-if="deviceList.length > 0">
            <el-table-column type="selection" header-align="center" align="center" width="30"></el-table-column>
            <el-table-column prop="id" header-align="center" align="center" label="ID" width="40"></el-table-column>
            <el-table-column prop="name" header-align="center" align="center" label="名称"></el-table-column>
            <el-table-column prop="siteName" header-align="center" align="center" label="站点名称"></el-table-column>
            <el-table-column prop="onlineStatus" header-align="center" align="center" label="在线">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.onlineStatus === 0" type="info" size="medium">否</el-tag>
                <el-tag v-if="scope.row.onlineStatus === 1" type="warning" size="medium">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="width" header-align="center" align="center" label="分辨率">
              <template slot-scope="scope">
                {{ scope.row.width }} * {{ scope.row.height }}
              </template>
            </el-table-column>
            <el-table-column prop="version" header-align="center" align="center" label="版本号"></el-table-column>
            <el-table-column prop="ram" header-align="center" align="center" label="内存"></el-table-column>
          </el-table>
          <el-button @click="delDevices" v-if="deviceList.length > 0" style="margin-top: 10px;" type="warning" size="mini">删除</el-button>
        </el-collapse-item>
      </el-collapse>
      <div>
        <el-button
          :disabled="deviceList.length == 0 || themeList.length == 0"
          type="success"
          style="position: absolute; right: 100px;margin-top: 20px"
          @click="nextStep"
          size="small"
        >
          下一步
        </el-button>
      </div>
    </div>
    <div v-show="step == 2">
      <el-form ref="form" label-width="100px" size="small">
        <el-form-item label="发布名称" :rules="{ required: true, message: '时间段不能为空', trigger: 'blur' }">
          <el-input size="small" v-model="publish.name"></el-input>
        </el-form-item>
        <el-form-item label="过期时间" :rules="{ required: true, message: '时间段不能为空', trigger: 'blur' }">
          <!--format="yyyy-MM-dd HH:mm:ss"-->
          <!--<el-date-picker-->
            <!--v-model="date_value"-->
            <!--type="date"-->
            <!--align="right"-->
            <!--unlink-panels-->
            <!--:clearable="false"-->
            <!--format="yyyy-MM-dd HH:mm:ss"-->
          <!--&gt;</el-date-picker>-->

          <el-date-picker
            v-model="guoqishijian"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="插播播放"><el-switch v-model="publish.interCut"></el-switch></el-form-item>
        <el-form-item label="播放日程">
          <el-radio-group v-model="publish.playMode">
            <el-radio-button label="1">全天轮播</el-radio-button>
            <el-radio-button label="2">自定义</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <div v-if="publish.playMode == 2">
          <el-form-item label="播放周期">
            <el-tabs type="border-card" v-model="publish.cycleMode">
              <el-tab-pane name="1">
                <span slot="label">
                  <i class="el-icon-date"></i>
                  按天
                </span>
                <el-checkbox-group v-model="day" disabled size="mini"><el-checkbox :checked="true" label="每天" border></el-checkbox></el-checkbox-group>
              </el-tab-pane>
              <el-tab-pane name="2">
                <span slot="label">
                  <i class="el-icon-tickets"></i>
                  按周
                </span>
                <el-checkbox-group v-model="cycleWeek" size="mini">
                  <el-checkbox label="1" border>周一</el-checkbox>
                  <el-checkbox label="2" border>周二</el-checkbox>
                  <el-checkbox label="3" border>周三</el-checkbox>
                  <el-checkbox label="4" border>周四</el-checkbox>
                  <el-checkbox label="5" border>周五</el-checkbox>
                  <el-checkbox label="6" border>周六</el-checkbox>
                  <el-checkbox label="0" border>周日</el-checkbox>
                </el-checkbox-group>
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
          <el-form-item v-for="(time, index) in times" :label="'时间段' + (index + 1)" :key="index" :rules="{ required: true, message: '时间段不能为空', trigger: 'blur' }">
            <el-time-picker
              is-range
              v-model="times[index]"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间播放时间段"
            ></el-time-picker>
            <el-button v-if="index > 0" type="warning" size="mini" @click.prevent="removeTime(time)">删除</el-button>
          </el-form-item>
          <el-form-item><el-button type="primary" size="small" @click.prevent="addTime()">添加</el-button></el-form-item>
        </div>
      </el-form>
      <div style="position: absolute; right: 100px;margin-top: 20px">
        <el-button @click="step = 1" size="small">上一步</el-button>
        <el-button type="success" @click="dataFormSubmit" size="small">发布</el-button>
      </div>
    </div>
    <div v-show="step === 1 && channelQuick">
      <div>
        <el-row type="flex" :gutter="10" class="row-bg">
          <el-col :span="5">
            <div style="margin-top: 15px">
              <!-- <i style="color: #00a65a" class="el-icon-plus" @click="() => addRoot()"></i> -->
              <el-tree ref="tree" :props="props1" :data="data" node-key="id" :expand-on-click-node="false" @node-click="quickSelect">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span style="display: inline-block;padding-right: 30px">
                    <icon-svg name="fileopen"></icon-svg>
                    &nbsp;
                    <span v-if="node.data.select" style="color: red">{{ node.label }}</span>
                    <span v-if="!node.data.select">{{ node.label }}</span>
                  </span>
                </span>
              </el-tree>
            </div>
          </el-col>
          <el-col :span="15">
            <div class="mod-config">
              <el-form :inline="true" :model="dataForm" @keyup.enter.native="quickGetDataList()">
                <el-col :span="6">
                  <el-form-item><el-input size="mini" v-model="dataForm.key" placeholder="名称" clearable @change="quickGetDataList()"></el-input></el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item><el-input size="mini" v-model="dataForm.mac" placeholder="MAC" clearable @change="quickGetDataList()"></el-input></el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item><el-input size="mini" v-model="dataForm.ipaddress" placeholder="ipaddress" clearable @change="quickGetDataList()"></el-input></el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item>
                    <el-select size="mini" v-model="dataForm.onlineStatus" placeholder="选择状态" @change="quickGetDataList()">
                      <el-option value="0" label="否" key="0"></el-option>
                      <el-option value="1" label="是" key="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item><el-button size="mini" @click="quickGetDataList()">查询</el-button></el-form-item>
                </el-col>
              </el-form>

              <el-table
                size="mini"
                :data="dataList"
                height="460"
                v-loading="dataListLoading"
                @selection-change="quickSelectionChangeHandle"
                style="width: 100%;"
                row-key="id"
                ref="multipleTable"
              >
                <el-table-column type="selection" reserve-selection width="30"></el-table-column>
                <el-table-column prop="id" label="ID" width="40"></el-table-column>
                <el-table-column prop="ipaddress" label="IP"></el-table-column>
                <el-table-column prop="groupName" label="分组"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column prop="mac" label="MAC"></el-table-column>
                <el-table-column prop="onlineStatus" label="在线">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.onlineStatus === 0" type="info" size="medium">否</el-tag>
                    <el-tag v-if="scope.row.onlineStatus === 1" type="warning" size="medium">是</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="width" label="分辨率">
                  <template slot-scope="scope">
                    {{ scope.row.width }} * {{ scope.row.height }}
                  </template>
                </el-table-column>
              </el-table>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <div><el-button type="primary" plain size="mini" @click="quickChangeSeleteionsList()">删除</el-button></div>
                <el-pagination
                  small
                  @size-change="sizeChangeHandle"
                  @current-change="currentChangeHandle"
                  :current-page="pageIndex"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="pageSize"
                  :total="totalPage"
                  layout="sizes, total, prev, pager, next"
                ></el-pagination>
              </div>
              <!-- 弹窗, 新增 / 修改 -->
            </div>
          </el-col>
          <el-col :span="1">
            <div style="margin-top: 160px"><!--<el-button  icon="el-icon-d-arrow-right" @click="addDevice" size="mini"  circle></el-button>--></div>
          </el-col>
          <el-col :span="3">
            <el-table size="mini" :data="dataListSelections" height="280" @selection-change="selectionChangeHandle" style="width: 100%;margin-top: 60px; min-height: 460px;">
              <el-table-column prop="name" header-align="center" align="center" label="已选设备">
                <template slot-scope="scope" style="width: 100%;">
                  <div style="display: flex; justify-content: space-between; align-items: center; width: 115px;">
                    {{ scope.row.name }}
                    <i class="el-icon-delete" style="cursor: pointer;" @click="quickChangeSeleteionsList(scope.row)"></i>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;margin-left: 15px;">
              <el-button type="primary" size="small" @click="nextStep()" :disabled="deviceList.length <= 0 || themeList.length <= 0">下一步</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <PublishViewInner v-if="(step === 3 || step === 4) && channelQuick" :publishViewInnerQuickNeedsCheck="quickNeedsCheck" :publishViewInnerId="publishId"></PublishViewInner>
    <select-theme @done="addTheme" ref="selectTheme"></select-theme>
    <select-device @done="addDevice" ref="selectDevice"></select-device>
  </div>
</template>
<style>
  .el-steps--simple{
    padding:13px 5%;
  }
  .el-step.is-simple{
    flex-basis: 25%!important;
  }
.el-steps--simple .el-step__title {
  width: 100% !important;
  font-size: 16px !important;
  line-height: 20px !important;
  margin-left: 0px !important;
}
</style>
<style scoped>
.el-steps--simple {
  /*background-color: #d6d6d6;*/
}
.el-card__body {
  padding-top: 10px !important;
}
</style>
<script>
/* eslint-disable no-extend-native */

import SelectTheme from './select-theme';
import SelectDevice from './select-device';
import PublishDeviceTheme from './publishdevicetheme';
import PublishViewInner from './publish-view-inner';
export default {
  name: 'publish-add',
  components: { SelectDevice, SelectTheme, PublishViewInner },
  data() {
    return {
      /*quickChannel-start*/
      dataForm: {
        key: '',
        mac: '',
        switchStatus: '',
        height: '',
        width: '',
        onlineStatus: '',
        ipaddress: ''
      },
      props1: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      publishId: 0,
      quickNeedsCheck: 1,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListSelections: [],
      selectedNode: {},
      dataListLoading: false,
      /*quickChannel-end*/
      data: [],

      channelQuick: false,
      channelQuickId: 0,
      times: [[new Date(), new Date()]],
      day: [],
      cycleWeek: [],
      step: 1,
      deviceList: [],
      deviceSelections: [],
      themeList: [],
      themeSelections: [],
      publish: {
        name: '发布' + new Date().pattern('yyyyMMddHHmmss'),
        playMode: '1',
        interCut: false,
        cycleMode: '1'
      },
      date_value: [new Date(), new Date()],
      guoqishijian: '',
      pickerOptions2: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      }
    };
  },
  watch: {
    '$route.query': {
      deep: true,
      immediate: true,
      handler(v1) {
        let that = this;
        if (v1.channel === 'QuickPublish' && v1.id) {
          that.$nextTick(() => {
            that.getGroups();
            that.quickGetDataList();
            that.themeList = [
              {
                ...v1
              }
            ];
            that.channelQuick = true;
            that.channelQuickId = parseInt(v1.id);
            that.$http({
              url: this.$http.adornUrl(`/sys/config/getExamine`),
              method: 'post'
            }).then(({ data }) => {
              if (data && data.code === 0) {
                that.quickNeedsCheck = data.examine=='0' ? 0 : 1;
              }
            });
          });
        }
      }
    }
  },
  activated() {
    this.quickGetDataList();
  },
  methods: {
    deviceSelectionChange(val) {
      this.deviceSelections = val;
    },
    themeSelectionChange(val) {
      this.themeSelections = val;
    },
    addDevice(data) {
      this.deviceList = data;
    },
    addTheme(data) {
      this.themeList = data;
    },
    selectDevice() {
      this.$refs.selectDevice.init(this.deviceList);
    },
    selectTheme() {
      this.$refs.selectTheme.init(this.themeList, this.$route.params);
    },
    delThemes() {
      this.removeItems(this.themeList, this.themeSelections);
    },
    delDevices() {
      this.removeItems(this.deviceList, this.deviceSelections);
    },
    indexOf(list, item) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === item.id) {
          return i;
        }
      }
      return -1;
    },
    remove(list, item) {
      let index = this.indexOf(list, item);
      if (index > -1) {
        list.splice(index, 1);
      }
    },
    removeItems(list, items) {
      for (let i = 0; i < items.length; i++) {
        this.remove(list, items[i]);
      }
    },
    nextStep() {
      this.step = 2;
    },
    removeTime(item) {
      if (this.times < 2) {
        return;
      }
      var index = this.times.indexOf(item);
      if (index !== -1) {
        this.times.splice(index, 1);
      }
    },
    addTime() {
      this.times.push([new Date(), new Date()]);
    },
    dataFormSubmit() {
      if(this.guoqishijian<new Date()){
        this.$message.error('过期时间不能小于当前时间');
        return;
      }
      const that = this;
      // this.$refs['form'].validate((valid) => {
      if (this.publish.name === '') {
        this.$message.error('请填写名称');
        return;
      }
      this.publish.devices = this.deviceList;
      this.publish.programEntitys = this.themeList;
      // this.publish.playTimes = this.times
      this.publish.startTime = new Date().pattern('yyyy-MM-dd HH:mm:ss');
      this.publish.endTime = this.guoqishijian.pattern('yyyy-MM-dd HH:mm:ss');
      if (this.publish.cycleMode === '2') {
        if (this.cycleWeek.length === 0) {
          this.$message.error('请选择星期');
          return;
        }
        this.publish.cycleWeek = this.cycleWeek.join(',');
      }
      if (this.publish.playMode === '2') {
        let playTimes = [];
        for (let i = 0; i < this.times.length; i++) {
          if (this.times[i] === null || this.times[i].length === null || this.times[i].length < 2) {
            this.$message.error('时间段未填写完整');
            return;
          }
          playTimes.push({ startTime: this.times[i][0].pattern('yyyy-MM-dd HH:mm:ss'), endTime: this.times[i][1].pattern('yyyy-MM-dd HH:mm:ss') });
        }
        this.publish.playTimes = playTimes;
      }
      // if (valid) {
      this.$http({
        url: this.$http.adornUrl(`/sys/publish/save`),
        method: 'post',
        data: this.$http.adornData(this.publish)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          that.publishId = data.id;
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              if (that.channelQuick) {
                if(that.quickNeedsCheck===0){
                  if(that.isAuth('sys:publish:examine')){
                    that.step = 3;
                  }else{
                    that.$router.push({path:'/sys-publish'});
                  }
                }else{
                  that.step = 4;
                }
              } else {
                that.$router.back();
              }
            }
          });
        } else {
          this.$message.error(data.msg);
        }
      });
      // }
      // })
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
      // if (this.refresh && val.length === 0) {
      //   return
      // }
      // this.refresh = false
      // this.removeItems(this.dataList)
      // this.addDevice()
    },
    quickSelect(data, node, ele) {
      if (this.selectedNode.data) {
        this.selectedNode.data.select = false;
        this.selectedNode.data.name = ' ' + this.selectedNode.data.name;
        this.selectedNode.data.name = this.selectedNode.data.name.trim();
      }
      data.select = true;
      data.name = ' ' + node.data.name;
      this.selectedNode = node;
      this.quickGetDataList();
    },
    quickGetDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/generator/stb/list'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          name: this.dataForm.key,
          mac: this.dataForm.mac,
          switchStatus: this.dataForm.switchStatus,
          onlineStatus: this.dataForm.onlineStatus,
          ipaddress: this.dataForm.ipaddress,
          stb_group_id: this.selectedNode.data ? this.selectedNode.data.id : null,
          height: this.dataForm.height,
          width: this.dataForm.width
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        if (this.dataListSelections.length > 0) {
          this.refresh = true;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.quickGetDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.quickGetDataList();
    },
    // 多选
    quickSelectionChangeHandle(val) {
      this.dataListSelections = val;
      this.deviceList = this.dataListSelections;
      // if (this.refresh && val.length === 0) {
      //   return
      // }
      // this.refresh = false
      // this.removeItems(this.dataList)
      // this.addDevice()
    },
    quickChangeSeleteionsList(item) {
      if (item) {
        this.$refs.multipleTable.toggleRowSelection(item);
      } else {
        this.dataListSelections.forEach(res => {
          this.$refs.multipleTable.toggleRowSelection(res);
        });
      }
      this.deviceList = this.dataListSelections;
    },
    getGroups() {
      const self = this;
      const url = '/generator/sgroup/goupList';
      this.$http({
        url: this.$http.adornUrl(url),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          self.data = data.data;
        } else {
          // alert(data.msg)
          this.$message({
            type: 'error',
            message: data.msg
          });
        }
      });
    }
  }
};
Date.prototype.pattern = function(fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, // 小时
    'H+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds() // 毫秒
  };
  var week = {
    '0': '/u65e5',
    '1': '/u4e00',
    '2': '/u4e8c',
    '3': '/u4e09',
    '4': '/u56db',
    '5': '/u4e94',
    '6': '/u516d'
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '/u661f/u671f' : '/u5468') : '') + week[this.getDay() + '']);
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return fmt;
};
</script>

<style scoped></style>
